import os
from functools import wraps

from flask import request, session

from app import app, PASSERBY_UPLOAD_FOLDER, ApiException
from app.Controllers.BaseController import BaseController
from app.Models.Compounds import Compounds
from app.Models.Files import FileForBM
from app.Models.Log import Log
from app.Models.Project import ProjectForBM
from app.Models.Users import Users
from app.Service.ChemometricsTutorialsServices.CommonService import readCsvOrExcelInfo
from app.Service.FileService import FileService
from app.Service.PasserByService import PasserByService
from app.Service.ProjectService import ProjectService
from app.Vendor.ApiException import illegalUserErr
from app.Vendor.Decorator import validator
from app.Vendor.UsersAuthJWT import UsersAuthJWT

'''
PasserBy的主要控制类，负责定义有什么服务，主要调用的是PasserByService的功能
'''


# 正式用户注册
@app.route('/api/user/register', methods=['POST'])
@validator(name="email", rules={'required': True, 'type': 'string', 'minlength': 10, 'maxlength': 20})
@validator(name="password", rules={'required': True, 'type': 'string', 'minlength': 6, 'maxlength': 20})
def register(params):
    ''' 注册 '''
    filters = {
        Users.email == params['email']
    }
    userData = Users().getOne(filters)
    if (userData == None):
        user = Users(
            email=params['email'],
            password=Users.set_password(params['password']),
            status=1)
        status = user.add(user)
        if status == True:
            return BaseController().successData(msg='注册成功')
        return BaseController().error('注册失败')
    return BaseController().error('账号已注册')


# 正式用户登录
@app.route('/api/user/login', methods=['POST'])
def login():
    ''' 登录 '''
    email = request.json.get('email')
    password = request.json.get('password')
    if (not email or not password):
        return BaseController().error('用户名和密码不能为空')
    else:
        result = UsersAuthJWT.authenticate(email, password)
        return result


@app.route('/api/user/test', methods=['POST'])
def test():
    ''' 测试'''
    flag = FileService().add("213123")
    return BaseController().successData(data=flag)


# 游客进行登录，并将信息储存到Session中
@app.route('/api/user/passerbyLogin', methods=['GET'])
def passerByLogin():
    userId, projectId, datalist = PasserByService().passerByLogin()
    session.permanent = True
    userMsg = dict(userId=userId, projectId=projectId, datalist=datalist)
    return BaseController().successData(msg='游客登录成功', data=userMsg)


# 检查用户的数据是否完备
@app.route('/api/user/isPrepared', methods=['GET'])
def isPrepared():
    state = PasserByService().getState()
    if state:
        if (PasserByService().examFileShape() is False):
            return BaseController().error(msg="文件的规格不统一，请检查")
        shape1, shape2, shape3 = PasserByService().examFileShape()
        shape = dict(FileShape1=shape1, FileShape2=shape2, FileShape3=shape3)
        return BaseController().successData(data=shape, msg="文件状态校验成功，可以开始分析")
    else:
        return BaseController().error(msg="有文件未上传，无法开始分析")


# 文件上传接口,根据dataType确定上传的文件是样本文件(data),标签文件(label),x轴坐标文件(coordinate)
@app.route('/api/upload/uploadFile/<dataType>', methods=['POST'])
def documentUploadFile(dataType):
    dataShape = dataType + "Shape"
    userId, projectId = PasserByService().getUserInfo()
    if (userId is None) or (projectId is None):
        return BaseController().error(msg='未进行初始化')

    try:
        dataFiles = request.files['file']
    except:
        return BaseController().error(msg='有文件未上传')

    saveDir = os.getcwd() + PASSERBY_UPLOAD_FOLDER + userId + "/" + projectId + "/"
    if not os.path.exists(saveDir):
        # 如果不存在则创建目录
        # 创建目录操作函数
        os.makedirs(saveDir)
    try:
        path, webPath = PasserByService().savefile(dataFiles, dataType, saveDir)
        shape1, shape2 = readCsvOrExcelInfo(path)
        shape = dict(FileShape1=shape1, FileShape2=shape2)
        data = dict(dataType=dataType, webPath=webPath, shape=shape)
        PasserByService().setFileShapeInfo(dataShape, shape)
        return BaseController().successData(data=data, msg='上传成功')
    except Exception as e:
        raise ApiException(500, "上传失败")


@app.route('/api/upload/exampleFile/<num>', methods=['GET'])
def setExampleFile(num):
    userId, projectId = PasserByService().getUserInfo()
    if (userId is None) or (projectId is None):
        return BaseController().error(msg='未进行初始化')
    try:
        if num == "1":
            PasserByService().setProjectFile()
        else:
            PasserByService().setProjectFile2()
        return BaseController().successData(msg='设置样例文件成功')
    except Exception as e:
        return BaseController().error(msg='设置样例文件出错')


@app.route('/api/upload/findSessionUpload', methods=['Get'])
def findSessionUpload():
    fileDict = PasserByService().getProjectInfo()
    return BaseController().successData(data=fileDict, msg="查询文件状态成功")


# 未完成
@app.route('/api/upload/deleteUploadFile', methods=['POST'])
def deleteUploadFile():
    userId, projectId = PasserByService().getUserInfo()
    filename = request.json["filename"]
    saveDir = os.getcwd() + PASSERBY_UPLOAD_FOLDER + userId + "/" + projectId + "/"
    PasserByService().deletefile(filename,saveDir)
    return BaseController().successData(msg='删除成功')
